<?
include("session.php"); 
include("xml_excel.php"); 
include("database.php");

define("LOCK_FILE_PATH", "./lock_file.txt");
$action = $_GET['action'];

if($action == "get_by_tel") {
	if($db->getOneValue("select id from hngj_callinfo where telephone='".$_GET['tel']."' and agent_id='".$_SESSION['hngj_agent_id']."'") == null) {
		echo "no record";
	} else {
		$sql = "select a.*,b.text_file,b.callout_number,b.task_status from hngj_callinfo a Left Join hngj_task b On a.task_id=b.id where telephone='".$_GET['tel']."' and agent_id='".$_SESSION['hngj_agent_id']."'"; 
		$arr = $db->getOneRecordArray($sql);
		echo array_to_json($arr);
	}

} else if($action == "get_by_id") {
	$sql = "select a.*,b.text_file,b.callout_number,b.task_status from hngj_callinfo a Left Join hngj_task b On a.task_id=b.id where a.id=".$_GET['id']; 
	$arr = $db->getOneRecordArray($sql);
	echo array_to_json($arr);

}
else if($action == "check_has_called") {
	//  and task_id=".$_GET['task_id'] // 按全系统来查找，不限任务；2014/10/11
	if($db->getOneValue("select id from hngj_callinfo where telephone='".$_GET['tel']."' and call_result=1") == null) {
		echo "no";
	} else {
		echo "yes";
	}
}
else if($action == "get_near_id") {
    $op = "<"; // next
	$val = "max(id)";
	if($_GET['direction'] == "prev") {
		$op = ">";
		$val = "min(id)";
	}
	$condition = "task_id=".$_GET['task_id']; // 注意：只提取同一个任务的记录； @2014/8/11
	if( ! is_admin_agent() ){
		if(empty($_SESSION['hngj_agent_id'])) {
			$condition .= " and agent_id='".$_GET['agent_id']."'";  // 针对session丢失问题，从list页面直接传入座席工号参数; @2014/8/9
		} else {
			$condition .= " and agent_id='".$_SESSION['hngj_agent_id']."'";
		}
	}
	$sql = "select max(id) from hngj_callinfo where call_result=0 and $condition and id <> ".$_GET['id'];  // and id $op ".$_GET['id']."  order by id desc limit 0,1
	//echo $sql;
	$id = $db->getOneValue($sql);
	/*if(empty($id)) {
		http_log("session : ". $_SESSION['hngj_agent_id']);
		http_log("get : ". $_GET['agent_id']);
		http_log($sql); // 出现ID为空的情况，跟踪一下sql语句;  @2014/8/11
	}*/
	echo $id;

}
else if($action == "get_free_id") { // 取当前任务中的一条未呼记录，用于自动读取; @2014/11/29
	$id = "";
	$fp = fopen( LOCK_FILE_PATH, "r" );
	if (!$fp) {  // 文件锁实现原子操作; @2014/12/3
		echo $id;
		exit;
	}
	flock ( $fp, LOCK_EX );
	$condition = "task_id=".$_GET['task_id'] ." and call_result=0 and agent_id=''"; 
	$sql = "select id from hngj_callinfo where $condition order by id limit 0,1";
	$id = $db->getOneValue($sql);
	if( ! empty($id) ) {
		$agent_id = "";
		if(empty($_SESSION['hngj_agent_id'])) {
			$agent_id = $_GET['agent_id']; 
		} else {
			$agent_id = $_SESSION['hngj_agent_id'];
		}
		// 将这条记录标识已分配状态
		$db->query("update hngj_callinfo set agent_id='$agent_id' where id=$id"); 
		// 可分配数量减1
		$db->query("update hngj_task set free_count=free_count-1 where id=".$_GET['task_id']);
	}
	flock ( $fp, LOCK_UN );
	fclose ( $fp );
	echo $id;

}
else if($action == "list") {
	$php_start_time = microtime(true);
	$condition = "1=1";
	if(isset($_GET['call_result'])) {
		$condition .= " and call_result=".$_GET['call_result'];
	}
	if(isset($_GET['telephone'])) {
		$condition .= " and (telephone='".$_GET['telephone']."' or recall_tel='".$_GET['telephone']."')";
	}
	if(isset($_GET['task_id'])) {
		$condition .= " and task_id=".$_GET['task_id'];
	}
	if(isset($_GET['date_range'])) {
		$arr = explode("_", $_GET['date_range']);
		$condition .= " and call_time between '".$arr[0]."' and '".$arr[1]."'";
	}
	if( ! is_admin_agent() ){
		if(empty($_SESSION['hngj_agent_id'])) {
			$condition .= " and a.agent_id='".$_GET['agent_id']."'";  // 针对session丢失问题，从list页面直接传入座席工号参数; @2014/8/9
		} else {
			$condition .= " and a.agent_id='".$_SESSION['hngj_agent_id']."'";
		}
	}
	
	if( isset($_GET['return_record_ids']) ) { // 用于录音的下载
		$db->query("select call_id,recall_id from hngj_callinfo where $condition"); // limit 0,10
		$arr = array();
		while($db->moveNext()) {
			if($db->f("call_id")!='') {
				$arr[] = $db->f("call_id");
			}
			if($db->f("recall_id")!='') {
				$arr[] = $db->f("recall_id"); // 如果存在二次营销外呼，将录音ID也加入
			}
		}
		echo join(",", $arr);

	} else if( isset($_GET['export_to_excel']) ) {       // 用于记录的导出
		$doc = array();
		$db->query("select *,b.task_name, b.callout_number,c.agent_name from hngj_callinfo a Left Join hngj_task b ON a.task_id=b.id Left Join hngj_agent c On a.agent_id=c.agent_id where $condition order by a.id desc");
	    $call_result = array(0=>"未呼", 1=>"营销成功", 2=>"营销失败", 3=>"预约回拔", 4=>"集团彩铃", 5=>"忙音", 6=>"空号", 7=>"停机", 8=>"无人接听", 9=>"直接挂机", 10=>"非负责人", 11=>"沟通障碍", 12=>"无效数据");
		$ring_flag = array(0=>"", 1=>"是", 2=>"否");
		while($db->next_record()) {
			$doc[] =  array(
					   $db->f("task_name"), 
					   $db->f("telephone"), 
					   $db->f("callout_number"), 
					   $call_result[$db->f("call_result")],
					   $db->f("call_time"), 
					   htmlspecialchars($db->f("cust_name")),
					   $ring_flag[$db->f("ring_flag")],
					   htmlspecialchars($db->f("cust_person")),
					   htmlspecialchars($db->f("cust_addr")),
				       $db->f("agent_id"),
					   $db->f("agent_name"),
					   str_replace(".", "。", htmlspecialchars($db->f("cust_desc"))),
					   str_replace(".", "。", htmlspecialchars($db->f("call_content"))) // 半角的句点在生成excel单元格时，会当成小数点处理，变成0值。
			);
		}
		$xml_excel = new Xml_Excel();
		$xml_excel->setWorksheetTitle("外呼营销结果");
		$xml_excel->addArray ( $doc );  
		$xml_excel->generateXML ("data_export_".date("YmdHis")); 
	} else {
		$sql = "select a.id,task_name, cust_name,ring_flag,telephone, agent_id, call_time, call_result, call_content, cust_person, cust_addr, call_tel, appt_time,call_id, b.callout_number, recall_id from hngj_callinfo a Left Join hngj_task b On a.task_id=b.id where $condition order by a.id desc"; 
		// echo $sql;
		echo to_grid_json($db, $sql, $dic_data, array("cust_name"=>"blue_color_mapper","telephone"=>"telephone_mapper"), true);
	}
	//http_log( "grid get time >>>>>>>>> " . (microtime(true)-$php_start_time) );

} else if($action == "add") { 
	unset($_POST['id']);
	$_POST['call_content'] = filter_special_chars($_POST['call_content']);
	$_POST['call_time'] = date("Y-m-d H:i:s");
	if(empty($_POST['appt_time'])) {
		unset($_POST['appt_time']);
	}
	$db->doInsert('hngj_callinfo', $_POST);
	echo 'ok';

}  else if($action == "edit") {
	$id = $_POST['id'];
	unset($_POST['id']);
	$_POST['call_content'] = filter_special_chars($_POST['call_content']);
	$_POST['call_time'] = date("Y-m-d H:i:s");
	if(empty($_POST['appt_time'])) {
		unset($_POST['appt_time']);
	}
	handle_call_result($id, $db, intval($_POST['call_result'])); // 更新操作前，进行统计字段计算
	$db->doUpdate('hngj_callinfo', $_POST, "id=$id");
	echo 'ok';
}



function handle_call_result($id, &$db, $new_result) {
	$arr = $db->getOneRecordArray("select call_result, task_id from hngj_callinfo where id=$id");
	$call_result = intval($arr['call_result']);
	if($new_result == $call_result) {
		return false; // 如果没有更改营销结果，直接返回
	}
	$task_id = intval($arr['task_id']);
	if($call_result == 1) { // 按原营销结果，进行统计字段更新
		$db->query("update hngj_task set success_count=success_count-1 where id=$task_id");
	} else if($call_result == 2) {
		$db->query("update hngj_task set fail_count=fail_count-1 where id=$task_id");
	} else if($call_result == 3) {
		$db->query("update hngj_task set appt_count=appt_count-1 where id=$task_id");
	} else if($call_result > 3) {
		$db->query("update hngj_task set other_count=other_count-1 where id=$task_id");
	}
	if($new_result == 1) {  // 按新的营销结果，进行统计字段更新
		$db->query("update hngj_task set success_count=success_count+1 where id=$task_id");
	} else if($new_result == 2) {
		$db->query("update hngj_task set fail_count=fail_count+1 where id=$task_id");
	} else if($new_result == 3) {
		$db->query("update hngj_task set appt_count=appt_count+1 where id=$task_id");
	} else if($new_result > 3) {
		$db->query("update hngj_task set other_count=other_count+1 where id=$task_id");
	}
	// 更新最近呼叫时间字段，用于取最新的任务排序；2014/11/6
	$db->query("update hngj_task set last_call_time='".date("Y-m-d H:i:s")."' where id=$task_id");
}


function telephone_mapper($v, $arr) {
	$str =  "<font color=red onclick=\"show_cust_info(".$arr['id'].")\">$v</font>";
	if($arr['call_result'] != 1) {
		//$str .= "&nbsp;<iframe src=\'http://222.240.139.227:9080/agent_event/callout_button.jsp?caller=".$arr['callout_number']."&called=".$v."&iconSize=15&calloutParams=no_confirm_before_call\' width=16 height=16 frameborder=0 marginheight=0 marginwidth=0 scrolling=no align=top></iframe>";
		$str .= "&nbsp;<img src=\\'/webkit/portal/images/query.png\\' width=16 height=16  align=top onclick=\\'show_cust_info(".$arr['id'].")\\' style=\\'cursor:hand\\' title=\\'打开客户信息面板\\'>";
	} else if($arr['call_id'] != '') {
		$str .= "&nbsp;<img src=\"voice.jpg\" width=16 height=16 onclick=\"show_voice(\\'". $arr['call_id'] ."\\', \\'". $arr['telephone'] ."\\')\"  align=absmiddle style=\"cursor:hand\" title=\"点击播放录音\">";
	} else if($arr['recall_id'] != '') {
		$str .= "&nbsp;<img src=\"voice2.jpg\" width=16 height=16 onclick=\"show_voice(\\'". $arr['recall_id'] ."\\', \\'". $arr['telephone'] ."\\')\"  align=absmiddle style=\"cursor:hand\" title=\"点击播放录音\">";
	}
	return $str;
}


?>